// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import config from "../config/config";
import func from "../config/func";

const { ccclass, property } = cc._decorator;

@ccclass
export default class AudioManage extends cc.Component {

    public static audioManage: AudioManage = null;

    bgAudio = null;

    onLoad() {
        if (AudioManage.audioManage == null) {
            AudioManage.audioManage = this;
        }
    }
    /**
    * 播放背景音效
    * @param path 路径
    * @param loop 是否循环播放
    */
    public async playBgMusic(path: string, loop: boolean) {
        if (!path || path == "") { return; }
        if (config.soundPath[path]) {
            this.bgAudio = cc.audioEngine.playMusic(config.soundPath[path], loop);
            return;
        }
        let sound = await func.loadResouce(path, cc.AudioClip) as cc.AudioClip;
        config.soundPath[path] = sound;
        this.bgAudio = cc.audioEngine.playMusic(sound, loop);
    }

    /**
     * 播放音效
     * @param path 路径
     */
    public async playEffectMusic(path: string) {
        if (!path || path == "") { return; }
        if (config.soundPath[path]) {
            cc.audioEngine.playEffect(config.soundPath[path], false);
            return;
        }
        let sound = await func.loadResouce(path, cc.AudioClip) as cc.AudioClip;
        config.soundPath[path] = sound;
        cc.audioEngine.playEffect(sound, false);
    }
    /**
     * 设置背景音效大小
     */
    public setBgAudioVolume() {
        cc.audioEngine.setMusicVolume(config.bgSound);
    }

    /**
     * 设置音效音量
     * @param value 音量 0~1
     */
    public setEffectVolume() {
        cc.audioEngine.setEffectsVolume(config.clickSound);
    }
    /**
    * 暂停播放背景音效
    */
    public stopBgAudio() {
        if (this.bgAudio != null) {
            cc.audioEngine.pause(this.bgAudio);
        }
    }
    /**
     * 恢复背景音效
     */
    public resumeBgAudio() {
        if (this.bgAudio == null) {
            this.playBgMusic(config.soundPath.bg, true);
        } else {
            cc.audioEngine.resumeMusic();
        }
    }
}
